from django.db import models
from django.db import connection

class TimeTableFields:
    date = 2000-00-00
    time_id = -1
    time = 0.0
    details = ' '
    type_activity = ' '
    user_id = -1
    project_id = -1
    
    def __init__(self, sql_row):
        self.date = sql_row[0]
        self.time_id = sql_row[1]
        self.time = sql_row[2]
        self.details = sql_row[3]
        self.type_activity = sql_row[4]
        self.user_id = sql_row[5]
        self.project_id = sql_row[6]
    
        
class TimeConfirmManager(models.Manager):
    def get_query_set(self):
        return super(TimeManagerManager, self).get_query_set()
        
    def unconfirmed(self, pm_id):
        cursor = connection.cursor()
        cursor.execute("""
                        SELECT d.day, t.id, t.time, t.details, a.name_activity, 
                            ap.user_id, ap.project_id
                        FROM timesheet_date d, timesheet_time t, 
                            timesheet_activity a, timesheet_activityproject ap, 
                            manager_projectmanageruser pmu, manager_projectmanager pm
                        WHERE d.id=t.day_id and
                            t.activity_project_id=ap.id and 
                            t.is_confirmed=0 and t.is_completed=1 and 
                            a.id=ap.activity_id and
                            ap.user_id=pmu.his_user_id and 
                            ap.project_id=pmu.project_id and 
                            pmu.manager_id=pm.id and 
                            pm.manager_id=%s
                        ORDER BY d.day DESC;
                        """, [pm_id])
        result_list = []
        for row in cursor.fetchall():
            elem = TimeTableFields(row)
            result_list.append(elem)
        return result_list

    def confirm(self, time_id):
        cursor = connection.cursor()
        require =   """
                        UPDATE timesheet_time t 
                        SET t.is_confirmed=1 
                        WHERE t.id IN (""" + time_id + """);
                    """
        cursor.execute(require)

        
    def turn_down_confirm(self, time_id):
        cursor = connection.cursor()
        require =   """
                        UPDATE timesheet_time t 
                        SET t.is_completed=0 
                        WHERE t.id IN (""" + time_id + """);
                    """
        cursor.execute(require)
    
    def take_time_list_query(self, time_id):
        require =   """
                        SELECT t.id, t.time, t.is_confirmed, t.is_completed
                        FROM timesheet_time t
                        WHERE t.id IN (""" + time_id + """);
                    """
        return require
        
        